import React from 'react'
import {
    View,
    Text,
    Button,
    TextInput,
    StyleSheet,
    Image,
    TouchableOpacity,
    TouchableWithoutFeedback,Platform
} from 'react-native'
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import ImagePicker from 'react-native-image-crop-picker';
import {guidName} from '../../util/Guid'

export default class ChatToolBar extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            content: '',
            voiceMode: false,
            speakMode: false,
            currentPeakMetering: 0,
            voiceText: '按住 说话',
            isAuthorised: undefined
        }
    }

    componentDidMount() {
        AudioRecorder.requestAuthorization().then((isAuthorised) => {
            this.setState({
                isAuthorised: isAuthorised
            })
            if (!isAuthorised) return;
        })

        AudioRecorder.onProgress = (data) => {
            //ios only
            // this.setState({currentPeakMetering: data.currentPeakMetering});
            // console.log('data.currentPeakMetering:' + data.currentPeakMetering)
            console.log('data.currentPeakMetering:' + data.currentTime)
        };

        AudioRecorder.onFinished = (data) => {
            // Android callback comes in the form of a promise instead.
            if (Platform.OS === 'ios') {
                // this._finishRecording(data.status === "OK", data.audioFileURL, data.audioFileSize);
            }
        };
    }

    //选择照片
    selectPhotoTapped() {
        ImagePicker.openPicker({
            width: 300,
            height: 400,
            cropping: true
        }).then(image => {
            console.log(image);
        });
    }

    //选择照片多选
    selectPhotosTapped() {
        ImagePicker.openPicker({
            multiple: true
        }).then(images => {
            console.log(images);
        });
    }

    //选择视屏
    selectVideoTapped() {
        ImagePicker.openPicker({
            mediaType: "video",
        }).then((video) => {
            console.log(video);
        });
    }

    selectFromCamera() {
        ImagePicker.openCamera({
            width: 300,
            height: 400,
            cropping: true
        }).then(image => {
            console.log(image);
        });
    }



    //准备录音
    prepareRecordingPath() {
        const voicePath = AudioUtils.DocumentDirectoryPath + '/' + guidName() + '.aac'
        AudioRecorder.prepareRecordingAtPath(voicePath, {
            SampleRate: 22050,
            Channels: 1,
            AudioQuality: "Low",
            AudioEncoding: "aac",
            AudioEncodingBitRate: 32000
        });
    }

    async _record() {
        try {
            const filePath = await AudioRecorder.startRecording();
        } catch (error) {
            console.error(error);
        }
    }

    async _stop() {
        const filePath = await AudioRecorder.stopRecording();
        if (Platform.OS === 'android') {
            // this._finishRecording(true, filePath);
        }
        return filePath;
    }

    async _play(voicePath) {
        setTimeout(() => {
            var sound = new Sound(voicePath, '', (error) => {
                if (error) {
                    console.log('failed to load the sound', error);
                }
            });
            setTimeout(() => {
                sound.play((success) => {
                    if (success) {
                        console.log('successfully finished playing');
                    } else {
                        console.log('playback failed due to audio decoding errors');
                    }
                });
            }, 100);
        }, 100);
    }


    render() {
        let sendOrMoreButton = this.moreButton();
        if (this._canSend()) {
            sendOrMoreButton = this.sendButton()
        }
        let textOrVoiceButtion = this.voiceButton();
        if (this.state.voiceMode) {
            textOrVoiceButtion = this.textButton();
        }
        let textOrVoiceInput = this.textInput();
        if (this.state.voiceMode) {
            textOrVoiceInput = this.voiceInput()
        }
        let emojiButton = this.emojiButton()
        return (
            <View style={styles.ButtonBar}>

                <View style={styles.editView}>
                    {textOrVoiceButtion}
                    {textOrVoiceInput}
                    {emojiButton}
                </View>
                <View style={styles.other}>
                    {sendOrMoreButton}
                </View>

            </View>
        )

    }

    _canSend() {
        return this.state.content
    }


    emojiButton() {
        return (
            <TouchableOpacity
                onPress={() => {
                }}>
                <Image style={styles.emoji} source={require('./emoji.png')}/>
            </TouchableOpacity>
        )
    }

    voiceInput() {
        return (
            <TouchableWithoutFeedback onPressOut={this._onVoicePressOut} onLongPress={this._onVoicePress}>
                <View style={[styles.voiceInput, this.state.speakMode && styles.voiceInputPress]}>
                    <Text>{this.state.voiceText}</Text>
                </View>
            </TouchableWithoutFeedback>
        )
    }

    textInput() {
        return (
            <TextInput value={this.state.content} onChangeText={this._onTextChange} multiline={true}
                       controlled={true} style={styles.textInput}/>
        )
    }

    voiceButton() {
        return (
            <TouchableOpacity
                onPress={() => {
                    this.setState({
                        voiceMode: true
                    })
                }}>
                <Image style={styles.voice} source={require('./voice.png')}/>
            </TouchableOpacity>
        )
    }

    textButton() {
        return (
            <TouchableOpacity
                onPress={() => {
                    this.setState({
                        voiceMode: false
                    })
                }}>
                <Image style={styles.voice} source={require('./text.png')}/>
            </TouchableOpacity>
        )
    }

    sendButton() {
        return (

            <TouchableOpacity
                onPress={() => {
                    this._onSendPress()
                }}>
                <Image source={require('./send.png')} style={styles.send}/>
            </TouchableOpacity>

        )
    }

    moreButton() {
        return (
            <TouchableOpacity
                onPress={this._onMorePress}>
                <Image style={styles.more} source={require('./more.png')}/>
            </TouchableOpacity>

        )
    }

    _onTextChange = (content) => {
        this.setState({
            content
        })
    }

    _onImagePress = () => {
        this.selectVideoTapped()
        // this.selectVideoTapped()
    }

    //点击更多
    _onMorePress = () => {
        // this.props.toCamera()
        // this.selectFromCamera()
        // this.selectPhotoTapped()
        this.selectPhotosTapped()
    }

    _onSendPress = () => {
        this.props.sendTextMsg(this.state.content)
        this.setState({
            content: ''
        })
    }

    _onVoicePress = () => {
        this.setState({
            voiceText: '松开 发送',
            speakMode: true
        })
        //执行录音准备
        this.prepareRecordingPath()
        //执行录音操作
        this._record();
    }

    //语音按钮松开
    _onVoicePressOut = () => {
        this.setState({
            voiceText: '按住 说话',
            speakMode: false
        })
         this._stop();
    }


}


const styles = StyleSheet.create({
    ButtonBar: {
        flexDirection: 'row',
        alignItems: 'flex-end',
        justifyContent: 'space-between',
        paddingLeft: 10,
        paddingVertical: 10,
        backgroundColor: 'white'
    },
    editView: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'flex-end'
    },
    voiceInput: {
        flex: 1,
        height: 32,
        borderRadius: 5,
        borderWidth: 1,
        borderColor: '#D7D7D7',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 5,
        marginBottom: -2
    },
    voiceInputPress: {
        backgroundColor: '#F0F2F5'
    },
    textInput: {
        flex: 1,
        fontSize: 18,
        paddingHorizontal: 5,
        borderBottomWidth: 1,
        borderBottomColor: 'red',
        marginHorizontal: 5,
        minHeight: 30,
        maxHeight: 30 * 3,
        paddingVertical: 0,
        // paddingTop: 5
    },
    voice: {
        width: 28,
        height: 28
    },
    emoji: {
        width: 28,
        height: 28
    },
    other: {
        width: 48,
        flexDirection: 'row',
        alignItems: 'flex-end',
        justifyContent: 'center'
    },
    more: {
        width: 28,
        height: 28
    },
    send: {
        width: 40,
        height: 28,
        backgroundColor: "#5EBD22",
        borderRadius: 3
    }
})
